import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

import 'interceptors/loginterceptor.dart';
import 'net_config.dart';

class NetManager {
  static NetManager _netManager;
  Dio _dio;
  BaseOptions options;

  NetManager() {
    if (_dio == null) {
      options = getOptions();
      _dio = new Dio(options);
      _dio.interceptors.add(new LogerInterceptor());
    }
  }

  void syncHeader() {
    if (options != null) {
      options.headers = NetConfig.headers();
    }
  }

  BaseOptions getOptions() {
    return BaseOptions(
      baseUrl: NetConfig.baseUrl,
      connectTimeout: NetConfig.connectTimeout,
      receiveTimeout: NetConfig.receiveTimeout,
      headers: NetConfig.headers(),
    );
  }

  static NetManager getInstance() {
    if (_netManager == null) {
      _netManager = NetManager();
    }
    return _netManager;
  }

  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic> queryParameters,
    Options options,
    CancelToken cancelToken,
    ProgressCallback onReceiveProgress,
  }) {
    return _dio.get(path,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onReceiveProgress: onReceiveProgress);
  }

  Future<Response<T>> post<T>(
    String path, {
    data,
    Map<String, dynamic> queryParameters,
    Options options,
    CancelToken cancelToken,
    ProgressCallback onSendProgress,
    ProgressCallback onReceiveProgress,
  }) {
    return _dio.post(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
    );
  }
}
